package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.hsp.system.repository.InstituicaoRepository;
import br.com.hsp.organizacao.Instituicao;

@ManagedBean
public class InstituicaoBean {

	private Instituicao instituicao = new Instituicao();
	
	private List<Instituicao> instituicaos; 

	public void add() {
		EntityManager manager = this.getManager();
		InstituicaoRepository instituicaoRepository = new InstituicaoRepository(manager);

		if (this.instituicao.getId() == null) {
			instituicaoRepository.add(this.instituicao);
		} else {
			instituicaoRepository.atualiza(this.instituicao);
		}
		this.instituicao = new Instituicao();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		InstituicaoRepository repository = new InstituicaoRepository(manager);
		this.instituicao = repository.procura(id);

	}
	

	public void remove() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		InstituicaoRepository repository = new InstituicaoRepository(manager);
		repository.remove(id);
		this.instituicao = null;
		this.instituicaos = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<Instituicao> getInstituicoes() {
		if (this.instituicaos == null) {
			EntityManager manager = this.getManager();
			InstituicaoRepository repository = new InstituicaoRepository(manager);
			this.instituicaos = repository.getLista();
		}
		return this.instituicaos;
	}
	
	public List<Instituicao> getClinicas(){
		List<Instituicao> clinicas;
		EntityManager manager = this.getManager();
		InstituicaoRepository repository = new InstituicaoRepository(manager);
		clinicas = repository.getListaClinicas();
		return clinicas;
	}

	public Instituicao getInstituicao() {
		return instituicao;
	}

	public void setInstituicao(Instituicao instituicao) {
		this.instituicao = instituicao;
	}

}
